﻿using System;

namespace Games.Common
{
    static class TimeCounter
    {
        static TimerStatus Status = TimerStatus.Init;
        static DateTime startTime;
        static double duration = 0;

        public static void Start(double? historyDuration = null)
        {
            Status = TimerStatus.Running;
            startTime = DateTime.Now;
            duration = historyDuration ?? 0;
        }

        public static double Value()
        {
            switch(Status)
            {
                case TimerStatus.Running:
                    return DateTime.Now.Subtract(startTime).TotalSeconds;
                case TimerStatus.Paused:
                case TimerStatus.Stopped:
                    return duration;
                default:
                    return 0;
            }
        }
        /// <summary>
        /// 停止，返回时长秒数整数
        /// </summary>
        /// <returns></returns>
        public static int Stop()
        {
            return (int)StopDouble();
        }
        /// <summary>
        /// 停止，返回时长秒数带小数
        /// </summary>
        /// <returns></returns>
        public static double StopDouble()
        {
            switch(Status)
            {
                case TimerStatus.Running:
                    var dur = DateTime.Now.Subtract(startTime).TotalSeconds;
                    duration += dur;
                    break;
                case TimerStatus.Paused:
                case TimerStatus.Stopped:
                    break;
                default:
                    duration = 0;
                    break;
            }
            Status = TimerStatus.Stopped;
            return duration;
        }

        public static void Pause()
        {
            if(Status == TimerStatus.Running)
            {
                var dur = DateTime.Now.Subtract(startTime).TotalSeconds;
                duration += dur;
                Status = TimerStatus.Paused;
            }
        }

        public static void Continue()
        {
            if(Status == TimerStatus.Paused)
            {
                Status = TimerStatus.Running;
                startTime = DateTime.Now;
            }
        }

        enum TimerStatus
        {
            Init = 0,
            Running = 1,
            Paused = 2,
            Stopped = 3
        }
    }
}